<?php
namespace app\common\model;

use core\db\Database;
use core\db\Model;
use PDO; 

class UserModel extends Model
{
    // 设置表名
    protected static $tableName = 'users';
    // 设置主键
    protected static $primaryKey = 'id';

    /**
     * 通过用户名查找用户
     * @param string $username 用户名
     * @return array|false 用户信息或false
     */
    public static function findByUsername($username)
    {
        $db = self::getDb();
        $table = static::$tableName;

        $stmt = $db->prepare("SELECT * FROM {$table} WHERE username = ?");
        $stmt->execute([$username]);
        return $stmt->fetch();
    }

    /**
     * 验证用户密码
     * @param string $password 原始密码
     * @param string $hashedPassword 数据库中存储的哈希密码
     * @return bool 验证结果
     */
    public static function verifyPassword($password, $hashedPassword)
    {
        return password_verify($password, $hashedPassword);
    }

    /**
     * 获取数据库连接
     * @return PDO
     */
    private static function getDb()
    {
        return Database::getInstance()->getConnection();
    }

    /**
     * 创建新用户
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|int 成功返回用户ID，失败返回false
     */
    public static function createUser($username, $password)
    {
        // 检查用户是否已存在
        if (self::findByUsername($username)) {
            return false;
        }

        // 密码加密
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // 插入数据
        $db = self::getDb();
        $table = static::$tableName;

        $stmt = $db->prepare("INSERT INTO {$table} (username, password, created_at) VALUES (?, ?, NOW())");
        if ($stmt->execute([$username, $hashedPassword])) {
            return $db->lastInsertId();
        }

        return false;
    }

    /**
     * 更新用户登录token
     * @param int $userId 用户ID
     * @return string 生成的token
     */
    public static function updateLoginToken($userId)
    {
        $token = md5(uniqid(rand(), true));
        $db = self::getDb();
        $table = static::$tableName;

        $stmt = $db->prepare("UPDATE {$table} SET login_token = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$token, $userId]);

        return $token;
    }

    /**
     * 验证用户token
     * @param int $userId 用户ID
     * @param string $token 要验证的token
     * @return bool 验证结果
     */
    public static function verifyLoginToken($userId, $token)
    {
        $db = self::getDb();
        $table = static::$tableName;

        $stmt = $db->prepare("SELECT COUNT(*) FROM {$table} WHERE id = ? AND login_token = ?");
        $stmt->execute([$userId, $token]);
        return $stmt->fetchColumn() > 0;
    }
}